const express = require('express');
const userService = require('../services/userService');
const cookieParser = require('cookie-parser');
const cookieSession = require('cookie-session');
const user = require('../models/user');

var router = express.Router();
//  1. 注册
router.post('/register',async (req,res,next) => {
    var user = req.body;
    if (user == undefined || user =={} || user == []){
        res.send({success:false,msg:"用户名与密码不能为空！"});
    }else {
        data = await userService.addUser(user);
        if (data.success){
            return {success:true,user:user};
        }else {
            return data;
        }
    }
});
//  2. 登录
router.post('/login',async (req,res,next) =>{
    var user = req.body;
    if (user == undefined || user =={} || user == []){
        res.send({success:false,msg:"用户名与密码不能为空！"});
    }else {
        var data = await userService.login(user);
        //  登录成功要进行session与cookie
        if (data.success){
            //  登录成功，对cookie操作，同时也对session操作
            if (user.remember == 'true'){
                res.cookie("user",data.user,{maxAge: 7*24*60*60*1000});
            }
            //   登录之后，立即记录
            req.session.user = data.user;   //  两种写法皆可
        }
        res.send(data);  // 登录失败
    }
});
//  3. 用户退出时清除session
router.use('/logout',(req,res) =>{
    var user = req.session['user'];
    if (user == null || user == {} || user == undefined){
        res.send("没有登录！");
    }else {
        req.session.destroy();
        res.send("/views/index.html");
    }
})
exports.router = router;